
const express = require("express");
const {multer, getUnix} = require('../../model/tools')
const ArticleCateModel = require("../../model/articleCateModel");
const ArticleModel = require("../../model/articleModel");

var router = express.Router();

router.get("/", async (req, res) => {

    var page = req.query.page || 1;
    var pageSize = 5
    var json={}
    var keywords = req.query.keywords;
    if(keywords){//mongoose模糊查询/20/ 这里要写正则表达式才行
        json=Object.assign(json,{"title":{$regex:new RegExp(keywords)}})
    }
    // var result = await ArticleModel.find({}).skip((page-1)*pageSize).limit(pageSize);
    var result = await ArticleModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: "cid",
                foreignField: "_id",
                as: "cate"
            }
        },
        {
            $match:json//如果需要做搜索的话，这里可以写搜索的条件
        },
        {
            $sort: {"add_time": -1}
        },{
            $skip: (page-1)*pageSize
        },{
            $limit: pageSize
        }
    ]);

    var count = await ArticleModel.count(json);
    console.log(count)
    res.render("admin/article/index.html",{
        list:result,
        totalPages:Math.ceil(count/pageSize),
        page:page,
        keywords:keywords
    })
})

router.get("/add", async (req, res) => {
    var result = await ArticleCateModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: "_id",
                foreignField: "pid",
                as: "items"
            }
        },
        {
            $match: {
                pid: "0"
            }
        }
    ]);
    res.render("admin/article/add.html",{
        cateList:result
    })
})

router.get("/edit", async (req, res) => {
    var id = req.query.id;
    var articleResult = await ArticleModel.find({"_id":id});
    console.log(articleResult)
    //获取分类信息
    var cateResult = await ArticleCateModel.aggregate([
        {
            $lookup: {
                from: "article_cate",
                localField: "_id",
                foreignField: "pid",
                as: "items"
            }
        },
        {
            $match: {
                pid: "0"
            }
        }
    ]);
    res.render("admin/article/edit.html",{
        cateList:cateResult,
        list:articleResult[0]
    })
})


//富文本上传图片
router.post("/doUpload", multer().single('file'),(req, res) => {
    var imgSrc = req.file ? req.file.path.split("\\").slice(1).join("/") : '';
    res.send({
        link: '/'+imgSrc
    })
})
//增加数据
router.post("/doAdd", multer().single('article_img'), async(req, res) => {
    var imgSrc = req.file ? req.file.path.split("\\").slice(1).join("/") : '';
    var result = new ArticleModel(Object.assign(req.body,{"article_img":imgSrc},{"add_time":getUnix()}));
    await result.save();
    res.render("admin/public/success.html",{
        redirectUrl:`/${req.app.locals.adminPath}/article`,
        message:"添加成功"
    })
})
//修改数据
router.post("/doEdit", multer().single('article_img'), async(req, res) => {

    if(req.file){
        var imgSrc = req.file ? req.file.path.split("\\").slice(1).join("/") : '';
        await ArticleModel.updateOne({"_id":req.body.id},Object.assign(req.body,{"article_img":imgSrc}));
    }else{
        await ArticleModel.updateOne({"_id":req.body.id},req.body);
    }
   
    res.render("admin/public/success.html",{
        redirectUrl:`/${req.app.locals.adminPath}/article`,
        message:"修改成功"
    })
})
module.exports = router